<template>
  <el-card style="box-shadow: none;">
    <el-row>
      <el-tooltip class="item" effect="dark" content="返回" placement="right-start">
        <el-button type="text" @click="returnCommodityList" style="margin-left: 10px">
          <svg t="1708609271658" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
               p-id="5331" width="30" height="30">
            <path d="M257.2 567.1h584.5c29 0 52.5-23.4 52.5-52.2V512c0-28.8-23.5-52.2-52.5-52.2H255.9L431 284.1c20.2-20.3 20.2-53 0-73.3l-0.4-0.4c-20.2-20.3-53.1-20.5-73.6-0.5l-0.5 0.5L71.8 496.1a26.013 26.013 0 0 0 0 36.7l55.7 55.9L352 813.8c20.4 20.5 53.7 20.6 74.3 0.4l0.4-0.4 1.7-1.7c20.3-20.3 20.3-53.1 0-73.4L257.2 567.1z" p-id="5332" fill="#515151"></path>
          </svg>
        </el-button>
      </el-tooltip>
      <h1 class="row__title" style="margin-left: 20px;margin-top: 3px; justify-content: center;">添加商品</h1>
    </el-row>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm" style="margin-top: 5px">
      <el-form-item label="商品类型：" prop="type">
        <el-radio-group v-model="ruleForm.type" @change="handleStatusChange">
          <el-radio-button :label="1">实物商品</el-radio-button>
          <el-radio-button :label="2">虚拟服饰</el-radio-button>
          <el-radio-button :label="3">优惠券</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品名：" prop="commodityName">
        <el-input v-model="ruleForm.commodityName" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item v-show="ruleForm.type === 2" label="选择服饰：" prop="clothingId">
        <el-cascader
            v-model="value"
            placeholder="请选择服饰" clearable
            :options="clothingList"
            :props="{ expandTrigger: 'hover' }"></el-cascader>
      </el-form-item>
      <el-form-item v-show="ruleForm.type === 3" label="选择优惠券：" prop="clothingId">
        <el-cascader
            v-model="id"
            placeholder="请选择优惠券" clearable
            :options="couponsList"
            :props="{ expandTrigger: 'hover' }"></el-cascader>
      </el-form-item>
      <el-form-item label="兑换积分：" prop="pointsRequired">
        <el-input v-model="ruleForm.pointsRequired" placeholder="请输入兑换商品积分"></el-input>
      </el-form-item>
      <el-form-item label="库存：" prop="stock">
        <el-input-number v-model="ruleForm.stock"  :step="1" min="0" controls-position="right"></el-input-number>
      </el-form-item>
      <el-form-item :class="{ hide: hideUpload }" label="商品图片：" prop="imgFileList">
        <el-upload
            ref="upload"
            action="#"
            multiple
            :limit="limit"
            :file-list="ruleForm.imgFileList"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-change="OnChange"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            accept="image/jpeg,image/png"
            :auto-upload="false">
          <svg t="1708595840001" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
               p-id="4203" width="50" height="50"><path d="M914.618182 477.090909H546.909091V109.381818c0-18.618182-16.290909-34.909091-34.909091-34.909091s-34.909091 16.290909-34.909091 34.909091v367.709091H109.381818c-18.618182 0-34.909091 16.290909-34.909091 34.909091s16.290909 34.909091 34.909091 34.909091h367.709091v367.709091c0 18.618182 16.290909 34.909091 34.909091 34.909091s34.909091-16.290909 34.909091-34.909091V546.909091h367.709091c18.618182 0 34.909091-16.290909 34.909091-34.909091s-16.290909-34.909091-34.909091-34.909091z" fill="#8a8a8a" p-id="4204"></path></svg>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品描述：" prop="description" type="textarea">
        <el-input
            type="textarea"
            placeholder="请输入商品描述"
            v-model="ruleForm.description"
            maxlength="150"
            show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitUpload()">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 圖片顯示 -->
  <div>
    <el-dialog
        v-model="dialogVisible"
        center
        width="30%"
    >
      <el-main>
        <div class="block">
          <el-image v-if="dialogImageUrl" :src="dialogImageUrl"></el-image>
        </div>
      </el-main>
    </el-dialog>
  </div>

</template>
<script>
import axios from "axios";
import {ElMessage} from "element-plus";
import clothesList from "@/components/clothesManagement/ClothesList.vue";

export default{
  name: "couponMonitor",
  computed: {
    clothesList() {
      return clothesList
    }
  },
  data() {
    return{
      ruleForm: {
        commodityName: '',
        type:1,
        clothingId:0,
        pointsRequired: '',
        stock:'',
        couponsId:0,
        productName: '',
        description:'',
        imgFileList: [],
      },
      value: [],
      clothingList:[],
      couponsList:[],
      type:1,
      dialogImageUrl: "",
      dialogVisible: false,
      rules: {
        type: [
          { required: true},
        ],
        commodityName: [
         { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        clothingId: [
          { required: true, trigger: 'blur'},
        ],
        pointsRequired: [
          { required: true, message: '兑换不能为空' },
          { pattern: /^[1-9][0-9]*$/, message: '兑换必须为正整数' }
        ],
        stock: [
          { required: true},
        ],
        imgFileList: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
      },
    }

  },
  watch: {
    // 监听type变化
    'ruleForm.type': function(newVal, oldVal){
      if (newVal !==  oldVal) {
        this.resetInputForm();
      }
    },
  },
  methods: {
    returnCommodityList(){
      this.$router.push({path:'/mallManagement/CommodityManagement'})
    },
    resetInputForm() {
      this.ruleForm = {
        couponsName: '',
        companyName:'',
        dateRange:'',
        value:'',
        minimumAmount: '',
        productName: '',
        description:'',
        condition: '',
        type:this.ruleForm.type,
        imgFileList: []
      };
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    returnClothingList(){
      this.$router.push({path:'/clothesManagement/ClothesList'})
    },
    //定義新增數據
    addCommodityInfo(category,commodityName,clothingId,couponsId,pointsRequired,description,stock){
      return {
        "category": category,"commodityName":commodityName, "clothingId":clothingId,"couponsId":couponsId,
        "pointsRequired": pointsRequired, "description":description,"stock":stock
      };
    },
    //点击上传图片
    submitUpload() {
      let formData = new FormData();
      let clothingId=0;
      let couponsId=0;
      let category=0;
      if(this.ruleForm.type==1){
        category=1;
      }
      if(this.ruleForm.type==2){
        clothingId=this.value[1];
        category=4;
      }
      if(this.ruleForm.type==3){
        couponsId=this.value[1];
        category=3;
      }

      let addData = this.addCommodityInfo(category, this.ruleForm.commodityName, clothingId,
          couponsId,this.ruleForm.pointsRequired, this.ruleForm.description, this.ruleForm.stock);

      console.log("新增商品信息：",addData);
      console.log("新增clothingId：",clothingId);
      console.log("新增couponsId：",couponsId);

      this.ruleForm.imgFileList.forEach((file) => {
        formData.append("file", file.raw);
      });

      formData.append("addData", JSON.stringify(addData)); // 将 addData 添加到 formData 中

      axios.post('/pointsMallManage/addCommodity', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
          .then(response => {
            // 处理后端返回的数据
            if (response.status === 200) {
              ElMessage({
                message: '添加成功',
                type: 'success',
              });
              this.resetForm('ruleForm');
              this.ruleForm.imgFileList = [];
            }
          })
          .catch(error => {
            // 处理错误情况
            console.log(error);
            this.$message.error();
          });
    },
    //预览图片时
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      console.log("预览图片时")
    },
    OnChange(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      this.ruleForm.imgFileList.push(file);

    },
    //删除图片时
    handleRemove(file) {
      if (file.id) {
        console.log("删除了已被上传过的图片");
        console.log(file.id);
        this.deleteImgFileList.push(file.id);
      }
      // this.ruleForm.imgFileList = fileList;
      // this.hideUpload = fileList.length >= this.limit;
    },
    //文件超出个数限制时
    handleExceed() {
      this.$message.warning(
          `当前限制选择 1 个文件`
      );
    },
    handleCommodityPicSuccess(res) {
      if (res && res.code === 200) {
        this.$message.success('上传成功');
      } else if (res && res.message) {
        this.$message.error(res.message);
      } else {
        this.$message.error('上传失败，未知错误');
      }
    },
    handleStatusChange(){
      if(this.ruleForm.type==2) this.getClothingList();
      if(this.ruleForm.type==3) this.getCouponsList();
    },

    async getClothingList() {
      try {
        const res = await axios.get('/selectorManage/getClothingList');

       // console.log("getClothingList返回值",res);

        if (res.status === 200) {
          this.clothingList = res.data.data;
          console.log("clothingList返回值",this.clothingList);
        } else {
          ElMessage('获取服装数据失败');
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage('获取服装数据失败');
      }
    },
    async getCouponsList() {
      try {
        const res = await axios.get('/selectorManage/getCouponsList');

        console.log("getCouponsList返回值",res);

        if (res.status === 200) {
          this.couponsList = res.data.data;
        } else {
          ElMessage('获取优惠券数据失败');
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage('获取优惠券数据失败');
      }
    },
  }

}
</script>
<style scoped>
.icon-svg:hover path {
  fill: #76cb02;
}


</style>